package structs

import "encoding/json"

func JsonObjectToStruct(value interface{}, output interface{}) error {
	body, err := json.Marshal(value)
	if err != nil {
		return err
	}
	return json.Unmarshal(body, output)
}

func ToStruct[T any](input interface{}) (*T, error) {
	val := new(T)
	return val, JsonObjectToStruct(input, val)
}

func ToMap(input interface{}) map[string]interface{} {
	val, _ := ToMapE(input)
	return val
}
func ToMapE(input interface{}) (map[string]interface{}, error) {
	val := make(map[string]interface{})
	return val, JsonObjectToStruct(input, &val)
}

func ToString(val interface{}) (string, error) {
	if val == nil {
		return "", nil
	}
	body, err := json.Marshal(val)
	return string(body), err
}

func FromJsonStr[V any](val string) (V, error) {
	var output V
	err := json.Unmarshal([]byte(val), &output)
	return output, err
}

func ToJsonStr(val interface{}) (string, error) {
	body, err := json.Marshal(val)
	return string(body), err
}
